﻿using System;
using System.Collections.Generic;
using System.Text;
using NRemedy;
using System.Threading;
using System.Windows.Forms;

namespace NRemedy.CodeGenerator.WinForm
{
    public class SearchFormThread : ARThread
    {

        private static string input = string.Empty;

        public PushFormListDelegate SearchCompeleted;

        public SearchFormThread()
        {
            _server = ARServerFactory.CreateARServer();
            SearchCompeleted += new PushFormListDelegate(SearchFormThread_SearchCompeleted);

        }

        protected virtual void SearchFormThread_SearchCompeleted(IEnumerable<ARFormDisplay> formList)
        {
        }

        public void Start(params object[] param)
        {
            if (param[0].ToString() == FilterType.Name.ToString()
                && param[1].ToString() == FilterOperation.contains.ToString()
                )
            {
                _thread = new Thread(GetListForm);
                input = param[2].ToString();
                _thread.Start();
            }
        }

        private void GetListForm(){
            _server.LogIn(_context);
            var result = _server.GetListForm(new ARFormFilterDelegate(FormFinalFilter));
            List<ARFormDisplay> forms = new List<ARFormDisplay>();
            foreach (var r in result)
            {
                ARFormDisplay f = new ARFormDisplay(r);
                forms.Add(f);
            }
            if(SearchCompeleted != null)
            {
                Control control = SearchCompeleted.Target as Control;
                if (control != null)
                    control.Invoke(SearchCompeleted, forms);
                else
                    SearchCompeleted(forms);
            }
            _server.LogOut();
        }

        public static bool FormFinalFilter(BMC.ARSystem.ARForm form){
            return CSharpClassGenerator.FormFilterBase(form) && CSharpClassGenerator.FormFilterWithRegex(form, ".*" + input + ".*");
        }


    }
}
